package utils

import (
	"gitee.com/simple-set/simple.proxy/src/config"
	"log/slog"
	"os"
)

var logFile *os.File

func InitLogger() {
	logLevel := slog.LevelInfo
	if config.Config.Debug {
		logLevel = slog.LevelDebug
		slog.SetLogLoggerLevel(logLevel)
	}
	if config.Config.Log != "" {
		if file, err := os.OpenFile(config.Config.Log, os.O_RDWR|os.O_CREATE|os.O_APPEND, 0666); err != nil {
			slog.Error("Failed to open log file " + err.Error())
			return
		} else {
			logFile = file
		}
		handler := slog.NewTextHandler(logFile, &slog.HandlerOptions{Level: logLevel})
		logger := slog.New(handler)
		slog.SetDefault(logger)
	}
	if logLevel == slog.LevelDebug {
		slog.Info("enable debugging mode")
	}
}

func CloseLogger() {
	if logFile != nil {
		if err := logFile.Close(); err != nil {
			slog.Error("Failed to close log file: " + err.Error())
		}
	}
}
